<template>
  <div class="page-container-padding">
    <div>
      <el-button icon="el-icon-plus" type="primary" @click="toAddNewVariety">
        添加
      </el-button>
    </div>
    <div style="margin-top: 5px">
      <el-table :data="varietyList" border>
        <el-table-column label="序号" width="70px">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="ID" prop="id" width="70px"></el-table-column>
        <el-table-column label="名称" prop="variety_name"></el-table-column>
        <el-table-column
          label="代码"
          prop="variety_en"
          sortable
        ></el-table-column>
        <el-table-column label="主力合约" prop="scontract"></el-table-column>
        <el-table-column
          label="空间归属"
          prop="spaces_zh"
          width="300px"
        ></el-table-column>
        <el-table-column
          label="组别"
          prop="group_name"
          sortable
        ></el-table-column>
        <el-table-column
          label="交易所"
          prop="exchange_name"
          sortable
        ></el-table-column>
        <el-table-column label="所有合约" width="80px" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              :icon="scope.row.loadingContract ? 'el-icon-loading' : ''"
              @click="toShowVarietyContracts(scope.row)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="操作" width="70px">
          <template #default="{ row }">
            <el-button type="text" @click="toShowEditVariety(row)">
              编辑
            </el-button>
            <!-- <el-button type="text" @click="toAllocateVariety(row)">分配</el-button> -->
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog :visible.sync="showEditDialog" title="编辑品种">
      <el-form :model="varietyObj" label-width="120px">
        <el-form-item label="名称">
          <el-input
            v-model.trim="varietyObj.variety_name"
            placeholder="输入品种的中文名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="交易代码">
          <el-input
            v-model.trim="varietyObj.variety_en"
            placeholder="输入品种的交易代码(唯一)"
            :disabled="!canEditVarietyEn"
          ></el-input>
        </el-form-item>
        <el-form-item label="分组">
          <el-select v-model="varietyObj.group_name">
            <el-option
              v-for="(g, index) in groupList"
              :key="index"
              :value="g"
              :label="g"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="交易所">
          <el-select v-model="varietyObj.exchange_name">
            <el-option
              v-for="(e, index) in exchangeList"
              :key="index"
              :value="e"
              :label="e"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="空间归属">
          <el-select
            v-model="currentVarietySpaces"
            multiple
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="v in allVarietySpaces"
              :key="v.code"
              :value="v.code"
              :label="v.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="价格单位">
          <el-input v-model.trim="varietyObj.price_unit" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="手数单位">
          <el-input v-model.trim="varietyObj.hand_unit" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="合约乘数">
          <el-input
            v-model.trim="varietyObj.hand_amount"
            size="mini"
          ></el-input>
        </el-form-item>
        <el-form-item label="策略资金">
          <el-input v-model.trim="varietyObj.fund" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="保证金比例">
          <el-input v-model.trim="varietyObj.bail_rate" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="启用">
          <el-checkbox
            v-model="varietyObj.is_active"
            :true-label="1"
            :false-label="0"
          >
            是
          </el-checkbox>
        </el-form-item>
        <el-form-item label="备注">
          <el-checkbox
            v-model="varietyObj.is_real"
            :true-label="1"
            :false-label="0"
          >
            实际上市品种
          </el-checkbox>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button
          type="primary"
          :loading="editLoading"
          @click="confirmEditVariety"
        >
          确定
        </el-button>
      </div>
    </el-dialog>

    <!-- 分配品种给用户的弹窗 -->
    <el-dialog :visible.sync="showAllocateDialog" title="品种分配" width="30%">
      <div style="padding: 4px 15px">
        <div style="font-size: 12px">
          将品种
          <span style="color: #1386d2; font-size: 14px">
            {{ allocationVariety.variety_name }}
          </span>
          分配给用户。
        </div>
        <br />
        <div>
          <el-row :gutter="8" align="middle" type="flex">
            <el-col :span="5">
              <div style="line-height: 100%">用户：</div>
            </el-col>
            <el-col :span="17">
              <el-select
                v-model="allocationVariety.allocateUserId"
                filterable
                remote
                placeholder="输入名称查询用户"
                :remote-method="queryAllocationUserByName"
                :loading="allocationVariety.queryUserLoading"
              >
                <el-option
                  v-for="item in allocationVariety.allocateUserList"
                  :key="item.id"
                  :label="item.admin_name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-col>
          </el-row>
          <br />
          <el-row :gutter="8" align="middle" type="flex">
            <el-col :span="5">有效期：</el-col>
            <el-col :span="17">
              <el-date-picker
                v-model="allocationVariety.allocateDate"
                type="date"
                placeholder="选择日期"
              ></el-date-picker>
            </el-col>
          </el-row>
          <br />
          <el-row :gutter="8" align="middle" type="flex">
            <el-col :span="5">有效空间：</el-col>
            <el-col :span="17">
              <el-select v-model="allocationVariety.name_space">
                <el-option
                  v-for="v in allVarietySpaces"
                  :key="v.code"
                  :value="v.code"
                  :label="v.name"
                ></el-option>
              </el-select>
            </el-col>
          </el-row>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="saveUserVariety">
          确 定
        </el-button>
      </div>
    </el-dialog>

    <!-- 品种合约详情的弹窗 -->
    <el-dialog :visible.sync="showVarietyContracts" title="品种的合约列表">
      <div style="padding: 5px 15px">
        <el-table
          border
          :data="currentContracts"
          :row-class-name="contractDialogClassName"
        >
          <el-table-column prop="contract_date" label="日期"></el-table-column>
          <el-table-column prop="variety_name" label="品种"></el-table-column>
          <el-table-column prop="variety_en" label="代码"></el-table-column>
          <el-table-column prop="lcontract" label="长合约"></el-table-column>
          <el-table-column prop="scontract" label="短合约"></el-table-column>
          <el-table-column label="主力">
            <template slot-scope="scope">
              {{ scope.row.activity === 0 ? '主力合约' : '合约' }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { varietySpaces } from '@/config/constantSetting'
  import { getRuizyVariety, getVarietyContract } from '@/api/variety'
  import { saveRuizyVariety } from '@/api/operations/variety'
  import { queryUserByName, AllocateUserVariety } from '@/api/operations/user'
  import { datetimeToStr } from '@/utils/datetimeUtils'
  export default {
    data() {
      return {
        contractUpdating: false,
        groupList: ['农业产品', '能源化工', '金属期货', '金融期货'],
        exchangeList: [
          '中金所',
          '大商所',
          '郑商所',
          '上期所',
          '上能源',
          '广期所',
          '非交易所',
        ],
        showEditDialog: false,
        canEditVarietyEn: true,
        varietyObj: {
          variety_name: '',
          variety_en: '',
          spaces: '',
          group_name: '',
          exchange_name: '',
          is_active: 1,
          is_real: 0,
          price_unit: '',
          hand_unit: '',
          hand_amount: 1,
          fund: 300000,
          bail_rate: 0,
        },
        allVarietySpaces: varietySpaces,
        currentVarietySpaces: [],
        editLoading: false,

        varietyList: [],
        showAllocateDialog: false,
        allocationVariety: {
          queryUserLoading: false,
          allocateUserId: null,
          allocateUserList: [],
          variety_name: '',
          variety_en: '',
          allocateDate: null,
          name_space: 'V03',
        },

        showVarietyContracts: false,
        currentVarietyEN: '',
        currentContracts: [],

        // 品种合约
        showEditContract: false,
        contractObj: {
          start_date: new Date(),
          end_date: new Date(),
          variety_en: '',
          lcontract: '',
          scontract: '',
          activity: 1,
        },
      }
    },
    mounted() {
      this.getAllVariety()
    },
    methods: {
      // 分配品种权限
      toAllocateVariety(vItem) {
        this.allocationVariety.variety_name = vItem.variety_name
        this.allocationVariety.variety_en = vItem.variety_en
        this.showAllocateDialog = true
      },

      // 保存用户品种权限
      saveUserVariety() {
        const userVarietyData = {
          user_id: this.allocationVariety.allocateUserId,
          variety_en: this.allocationVariety.variety_en,
          name_space: this.allocationVariety.name_space,
          expire: datetimeToStr(this.allocationVariety.allocateDate, true, '-'),
        }
        AllocateUserVariety(userVarietyData).then((res) => {
          this.$baseMessage(res.msg, 'success')
          this.showAllocateDialog = false
        })
      },

      // 通过用户名称查询用户
      queryAllocationUserByName(userName) {
        if (userName.length < 1) return
        queryUserByName(userName).then((res) => {
          this.allocationVariety.allocateUserList = res.data
        })
      },

      toAddNewVariety() {
        this.canEditVarietyEn = true
        this.varietyObj = {
          variety_name: '',
          variety_en: '',
          group_name: '',
          exchange_name: '',
          is_active: 1,
          is_real: 0,
          price_unit: '',
          hand_unit: '',
          hand_amount: 1,
          fund: 300000,
          bail_rate: 0,
        }
        this.showEditDialog = true
      },

      confirmEditVariety() {
        this.varietyObj.spaces = this.currentVarietySpaces.join(',')
        saveRuizyVariety(this.varietyObj).then((res) => {
          this.$baseMessage(res.msg, 'success')
          this.showEditDialog = false
          this.clearVarietyObj()
          this.getAllVariety()
        })
      },

      // 清除当前编辑的对象数据
      clearVarietyObj() {
        this.varietyObj.variety_name = ''
        this.varietyObj.variety_en = ''
        this.varietyObj.group_name = ''
        this.varietyObj.exchange_name = ''
        this.varietyObj.is_active = 1
        this.varietyObj.is_real = 0
        ;(this.varietyObj.price_unit = ''),
          (this.varietyObj.hand_unit = ''),
          (this.varietyObj.hand_amount = 1),
          (this.varietyObj.fund = 300000),
          (this.varietyObj.bail_rate = 0)
      },

      getAllVariety() {
        getRuizyVariety().then((res) => {
          const varietyData = res.data
          this.varietyList = varietyData.map((item) => {
            item.loadingContract = false
            return item
          })
        })
      },

      toShowEditVariety(vItem) {
        this.canEditVarietyEn = false
        this.varietyObj = Object.assign(this.varietyObj, vItem)
        if (this.varietyObj.spaces) {
          this.currentVarietySpaces = this.varietyObj.spaces.split(',')
        } else {
          this.currentVarietySpaces = []
        }
        this.showEditDialog = true
      },

      // 弹窗显示合约
      toShowVarietyContracts(row) {
        this.currentContracts = []
        this.currentVarietyEN = row.variety_en
        row.loadingContract = true
        const param = {
          v: this.currentVarietyEN,
        }
        getVarietyContract(param)
          .then((res) => {
            if (!res.data || res.data.length < 1) {
              this.$baseMessage('该品种还没合约记录!', 'info')
            } else {
              this.currentContracts = res.data
              this.showVarietyContracts = true
            }
            row.loadingContract = false
          })
          .catch(() => {
            row.loadingContract = false
            this.$baseMessage('获取合约失败!', 'error')
          })
      },

      contractDialogClassName({ row, index }) {
        return row.activity === 0 ? 'activity-contract' : ''
      },
    },
  }
</script>

<style scoped>
  .el-table >>> .activity-contract {
    color: #ff430d !important;
  }
</style>
